<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use common\helpers\Location;
use common\models\system\City;
use yii\db\Expression;

class CityService
{

    /**
     * 获取城市所有列表
     * @return array
     */
    public static function selectList(): array
    {
        return City::find()->select(['id', 'name','short_name','parent_id','level','area_code','status'])->orderBy('parent_id asc, id asc')->asArray()->all();
    }


    /**
     * 根据坐标获取最近的城市
     * @param float $latitude
     * @param float $longitude
     * @return array
     */
    public static function nearCity(float $latitude, float $longitude): array
    {
        $city = City::find()->select(['id','name','short_name','merge_name','parent_id',new Expression(Location::distanceSql($latitude, $longitude, 'lat', 'lng'))])->where(['level'=>1])->orderBy('distance asc, id asc')->limit(1)->asArray()->one();
        return $city?:[];
    }


    /**
     * 根据IP获取城市信息
     * @param $ip
     * @return array
     */
    public static function getCityByIp($ip): array
    {
        $address = Location::getAddressByIp($ip);
        if (!$address) return [];

        $province = [];
        $provinceList = City::find()->select(['id','name'])->where(['parent_id' => 0])->asArray()->all();
        foreach ($provinceList as $value) {
            $name = str_replace(['市','自治州','省','地区'],'',$value['name']);
            if (strpos($address,$name) > -1) {
                $province = $value;
                break;
            }
        }
        if (!$province) return [];

        $city = [];
        $cityList = City::find()->select(['id','name','short_name','merge_name','parent_id'])->where(['parent_id' => $province['id']])->asArray()->all();
        foreach ($cityList as $value) {
            $name = str_replace(['市','自治州','省','地区'],'',$value['name']);
            if (strpos($address,$name) > -1) {
                $city = $value;
                break;
            }
        }
        return $city;
    }
}
